package com.eascs.afterloan.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;
import com.eascs.admin.common.service.BaseSevice;
import com.eascs.admin.common.utils.StringUtils;
import com.eascs.admin.o2o.internal.util.BaseUserUtil;
import com.eascs.admin.o2o.internal.util.StatusContexts;
import com.eascs.admin.o2o.loan.entity.O2oLoanapplyEntity;
import com.eascs.admin.o2o.loan.service.O2oLoanapplyService;
import com.eascs.afterloan.dao.AdvanceSettleDao;
import com.eascs.afterloan.entity.AdvancedPayment;
import com.eascs.afterloan.form.AdvanceSettleForm;
import com.eascs.app.dao.PageResult;
import com.eascs.app.dao.SqlPageQuery;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.web.sso.User;
import com.eascs.web.sso.UserHolder;
import com.eascs.workflow.common.entity.wf.ProcessTemplate;
import com.eascs.workflow.common.service.wf.WorkFlowService;
import com.eascs.workflow.common.vo.ModelResult;
import com.eascs.workflow.common.vo.WFRequestParam;
import jodd.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class AdvanceSettleService extends BaseSevice{
	private final Logger logger = LoggerFactory.getLogger(AdvanceSettleService.class);

	@Autowired
	AdvanceSettleDao advanceSettleDao;
	@Autowired
	private O2oLoanapplyService o2oLoanapplyService;
	@Autowired
	BaseUserUtil userUtils;
	@Reference
	private WorkFlowService workFlowService;
	@Value("${o2o.admin.advancedPaymentUrl}")
	private String advancedPaymentUrl;

	
	/**
	 * @Title: queryEntity
	 * @Description:查询该流程信息
	 * @author 张庆奇
	 * @param loanapplyNo
	 * @param billStatus
	 * @return
	 * @return AdvancedPayment
	 * @throws
	 * @date 2017年2月16日 上午9:40:56
	 */
	public AdvancedPayment queryEntity(String loanapplyNo,String billStatus){
		String sql="select * from o2o_advanced_payment t where t.loanapply_no=?";
		if(!StringUtil.isBlank(billStatus)){
			sql = sql +"  and bill_status = '"+billStatus+"' ";
		}
		return advanceSettleDao.findEntity(sql, AdvancedPayment.class, loanapplyNo.trim());
	}

	public void save(AdvancedPayment advancedPayment) {
		logger.info("advancedPayment:" + JSONObject.toJSONString(advancedPayment));
		advanceSettleDao.insert(advancedPayment);
	}
	
	
	@Transactional(transactionManager = "o2oTransactionManager")
	public void updateWorkFlowStatus(String status, String loanapplyNo) {
		if (status.equals(StatusContexts.WFTYPE_STATUS_NEW)) { // 新建然后run
			String sql = "update o2o_advanced_payment o set o.updator=?,o.update_time=? where o.loanapply_no=? and bill_status = ? ";
			advanceSettleDao.execute(sql, userUtils.getUpdateOr(), userUtils.getUpdateTime(), loanapplyNo, status );
		} else {
			String sql = "update o2o_advanced_payment o set o.bill_status=?,o.updator=?,o.update_time=? where o.loanapply_no=? and bill_status = ? ";
			advanceSettleDao.execute(sql, status, userUtils.getUpdateOr(), userUtils.getUpdateTime(), loanapplyNo,"NEW");
		}
	}
	
	public AdvancedPayment queryById(String id) {
		return advanceSettleDao.getById(AdvancedPayment.class, id);
	}
	
	public int updateById(AdvancedPayment advancedPayment) {
		return advanceSettleDao.updateById(advancedPayment);
	}
	
	
	/**
	 * 启动提前还款结清流程
	 */
	public ModelResult<Boolean> advancedPayment(O2oLoanapplyEntity loan) { // 根据单号去启动流程
		logger.info("贷款编号：[{}],贷款类型：[{}],启动提前还款结清流程", loan.getBillCode(),loan.getLoanType());
		
		WFRequestParam param = new WFRequestParam();
		param.setReferId(loan.getLoanapplyNo());
		param.setReferCode(loan.getBillCode());	
		param.setReferUrl(advancedPaymentUrl + "?billCode=" + loan.getBillCode()+"&type=1");
		param.setSystemModule(ProcessTemplate.SYSTEM_MODULE_O2O);
		param.setProcessType(String.valueOf(ProcessTemplate.PROECESS_TYPE_TQ_PAYMENT));
		param.setProcessVersion("v1");
		User user = UserHolder.getUser();
		param.setAppliedby(user.getNo());
		param.setAppliedbyName(user.getCname());
		param.setOrgNo(loan.getLtd());

		StringBuffer appliedDes = new StringBuffer("借款人:");
		appliedDes.append(o2oLoanapplyService.findLoanUserEntity(loan.getLoanapplyNo(),loan.getLoanId()).getUserFullName());
		appliedDes.append("，付款人:" + queryEntity(loan.getLoanapplyNo(), null).getPayName());
		param.setAppliedDes(appliedDes.toString());
		logger.info("提前还款结清WFRequestParam对象：[{}]", param.toString());
		ModelResult<Boolean> modelResult = workFlowService.instance(param);
		return modelResult;
	}
	
	
	public PageResult<Object[]> findByPageList(AdvanceSettleForm advancedPayment) {
		SqlPageQuery<Object[]> pageQuery = new SqlPageQuery<>(Object[].class, advancedPayment.getPageSize(), advancedPayment.getShowO2oPage());
		StringBuffer querySql = new StringBuffer();
	 if(advancedPayment.getType()==null){
		 querySql.append(" select ocb.id,ocb.bill_code,ocb.loaner_name,pay_name,ocb.pay_date,ocb.settle_date,case ocb.bill_status when 'NEW' then '新建' when 'RUN' then '审核中' when 'CLO' then '流程结束' end as bill_status"); 
	 }else{
		 querySql.append(" select ocb.bill_code,ocb.loaner_name,case ocb.bill_status when 'NEW' then '新建' when 'RUN' then '审核中' when 'CLO' then '流程结束' end as bill_status,pay_name,ocb.pay_date,ocb.settle_date"); 
 
	 }
		
		querySql.append(" from o2o_advanced_payment ocb  LEFT JOIN o2o_loanapply l on l.loanapply_no = ocb.loanapply_no ");
		querySql.append(" where 1=1  ");
		
		querySql.append(" and (l.creat_ro="+UserHolder.getUser().getNo());
		if (!StringUtils.isEmpty(advancedPayment.getUsersno())) {
			querySql.append(" or l.operator_no in ("+advancedPayment.getUsersno()+"))");
		}else {
			querySql.append(" or /**DATA_PERMISSION(l.LTD)**/ 1=1 ) ");
		}
		
		if (!StringUtil.isEmpty(advancedPayment.getBillCode())) {
			querySql.append(" AND ocb.bill_code = ? ");
			pageQuery.addParam(advancedPayment.getBillCode());
			logger.debug("oa params bill_code={}", advancedPayment.getBillCode());
		}
		if (!StringUtil.isEmpty(advancedPayment.getLoanerName())) {
			querySql.append(" AND ocb.loaner_name like ? ");
			pageQuery.addLikeParam(advancedPayment.getLoanerName());
			logger.debug("oa params bill_code={}", advancedPayment.getLoanerName());
		}
		if (!StringUtil.isEmpty(advancedPayment.getJqstartdate())) {
			querySql.append(" AND ocb.settle_date >= ? ");
			pageQuery.addParam(advancedPayment.getJqstartdate());
		}
		if (!StringUtil.isEmpty(advancedPayment.getJqenddate())) {
			querySql.append(" AND ocb.settle_date <=? ");
			pageQuery.addParam(advancedPayment.getJqenddate());
		}
		querySql.append(" ORDER BY ocb.creat_time DESC ");
		pageQuery.setQuerySql(querySql.toString());
		return advanceSettleDao.findDataWithPage(pageQuery);
	}
	
}
